# -*- coding: utf-8 -*-
"""商品分类列表页对象（df_goods/list.html）"""

from urllib.parse import urlparse, parse_qs
from selenium.webdriver.common.by import By

from .base import BasePage


class ListPage(BasePage):
    """针对商品列表页的常用操作封装"""

    # 顶部三种排序链接（默认/价格/人气）
    SORT_LINKS = (By.CSS_SELECTOR, ".sort_bar a")  # 顺序与模板保持一致
    GOODS_PRICES = (By.CSS_SELECTOR, "ul.goods_type_list li .prize")

    def sort_links(self):
        return self.driver.find_elements(*self.SORT_LINKS)

    def active_sort_index(self) -> int:
        """返回当前激活的排序索引 0,1,2; 若未找到返回 -1"""
        for idx, el in enumerate(self.sort_links()):
            if "active" in el.get_attribute("class"):
                return idx
        return -1

    def click_sort(self, index: int):
        """点击排序链接 0=默认 1=价格 2=人气"""
        self.sort_links()[index].click()

    def current_sort_param(self) -> str:
        """解析 URL 中 sort 参数（最后一段）"""
        path = urlparse(self.driver.current_url).path  # /list1_1_2
        # 根据路由规则，最后一段下划线后为 sort
        try:
            sort = path.split("_")[-1].rstrip('/')
            return sort
        except Exception:
            return ""

    def get_prices(self) -> list[float]:
        """抓取当前页面展示的商品价格列表（浮点型）"""
        els = self.driver.find_elements(*self.GOODS_PRICES)
        prices = []
        for el in els:
            txt = el.text.replace("¥", "").replace("元", "")
            try:
                prices.append(float(txt))
            except ValueError:
                continue
        return prices 